<template>
	<view class="content">
		<view style="">
			<!--			<u-button @click="download" :disabled="itemId===''">下载当前投票页面二维码</u-button>-->
			<!--			<u-button @click="queryUserVoted">查询当前投票情况</u-button>-->

			<!--			<u-switch v-model="sortChecked" @change="changeSort"></u-switch>-->
			<!--			{{ sortChecked ? '升序排名' : '降序排名' }}-->
			<u-slider v-model="sliderV"></u-slider>
		</view>
		<u-grid :col="2">
			<u-grid-item v-for="(voteItem,index) in list" :key="index">
				<view class="item" @click="toVote(voteItem.id,index)">
					<view class="item-right">
						<view :style="{fontSize:sliderV+'px' }"> 候选人:{{ voteItem.name }}</view>
						<!--						<view v-if="item.type===1">当前投票数:{{ voteItem.voteCount }}</view>-->
						<!--						<view v-if="item.type===2">当前已打分人数:{{ voteItem.voteCount }}</view>-->
						<view>你的打分为：{{
								totalValue(voteItem.id)
							}}
						</view>
					</view>
				</view>
			</u-grid-item>
			<view>
			</view>
		</u-grid>
		<view>
			<u-button @click="sureVote" :disabled="isVote">确认投票</u-button>
		</view>


		<!--		<u-popup v-model="showPopup" mode="center" border-radius="10" length="60%">-->
		<!--			<view style="padding: 20px">-->
		<!--				<view style="display: flex;align-items: center">-->
		<!--					<span style="margin-right: 10px">{{ checkedVoted ? '查看未投票' : '查看已投票' }}</span>-->
		<!--					<u-switch v-model="checkedVoted"></u-switch>-->
		<!--				</view>-->

		<!--				<view v-show="checkedVoted">当前已投票人数:{{ votesUser.length }}</view>-->
		<!--				<view v-show="!checkedVoted">当前未投票人数:{{ notVotesUser.length }}</view>-->
		<!--				<view v-for="(voted,index) in votesUser" :key="index" v-show="checkedVoted">-->
		<!--					<view>{{ voted.name }}</view>-->
		<!--				</view>-->
		<!--				<view v-for="(voted,index) in notVotesUser" :key="index" v-show="!checkedVoted">-->
		<!--					<view>{{ voted.name }}</view>-->
		<!--				</view>-->
		<!--			</view>-->
		<!--		</u-popup>-->

		<u-popup v-model="showUserVotedPopup" mode="center" :closeOnClickOverlay="false"
						 border-radius="10" length="70%">
			<view style="padding: 20px;font-size: 1.3rem">
				<view style="margin: 15px 0" v-for="(scoreItem,index) in scoreListNow" :key="index">
					<view>
						<span style="font-size: 18px">
							{{ scoreItem.scoreName }}
						</span>
					</view>
					<u-input :disabled="isVote" v-model="scoreItem.score" type="number" :border="true"/>
					<span style="font-size: 13px">最高分:{{
							scoreContent[index].minScore
						}},最高分:{{ scoreContent[index].maxScore }}</span>
					<view>
					</view>
				</view>
				<u-button @click="sureVoteScore">确认打分</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
import {BASE_URL, checkLogin, getStore, setStore} from "../../api/common";

var self;
var timer;
export default {
	data() {
		return {
			sliderV: 18,
			list: [],
			itemId: "",
			item: {},
			isVote: true,
			votesUser: [],
			notVotesUser: [],
			showPopup: false,
			checkedVoted: true,
			showUserVotedPopup: false,
			scoreContent: [],
			sortChecked: true,
			isLoading: false,
			scoreMapList: {}, // 打分的map
			scoreListNow: [], // 当前打分的list,
			clickCurrentIndex: 0,
		}
	},
	methods: {
		download() {
			uni.showLoading({
				title: '下载中',
				mask: true
			});
			var oA = document.createElement("a");
			oA.download = '二维码'; // 设置下载的文件名，默认是'下载'
			oA.href = self.item.qrCode;
			document.body.appendChild(oA);
			oA.click();
			oA.remove(); // 下载之后把创建的元素删除
			uni.hideLoading();
		},

		// 打开投票框
		async toVote(id, index) {
			console.log(self.scoreContent)
			// self.clickCurrentIndex = index;
			if (self.scoreContent.length === 0) {
				uni.showLoading({
					title: '查询中',
					mask: true
				});
				const result = await self.$u.get(BASE_URL + "/vote/getScoreContent", {
					id,
					itemId: self.itemId
				}, {'satoken': uni.getStorageSync('satoken')})

				uni.hideLoading();
				if (result.code === 200) {
					self.scoreContent = result.data;
				} else {
					uni.showToast({
						title: result.msg ?? '查询失败',
						icon: 'none',
						duration: 2000
					});
				}
			}
			const mapList = self.scoreMapList[id];
			if (mapList) {
				self.scoreListNow = mapList;
			} else {
				self.scoreListNow = [];
				for (let i = 0; i < self.scoreContent.length; i++) {
					const score = self.scoreContent[i];
					self.scoreListNow.push({
						itemId: self.itemId,
						voteId: id,
						scoreId: score.id,
						scoreName: score.name,
						voteName: self.list[index].name,
						score: 0,
					})
				}
				self.scoreMapList[id] = [...self.scoreListNow];
			}
			self.showUserVotedPopup = true;
		},
		sureVoteScore() {
			if (self.isVote) {
				self.showUserVotedPopup = false;
				return;
			}
			// 判断 scoreListNow 是否全部打分,并且是否在打分范围内
			for (let i = 0; i < self.scoreListNow.length; i++) {
				let score = self.scoreListNow[i];
				if (!isNaN(score.score)) {
					score.score = parseFloat(score.score + '');
				}
				console.log(isNaN(score.score), score.score < self.scoreContent[i].minScore, score.score > self.scoreContent[i].maxScore)
				console.log(score.score, self.scoreContent[i].minScore, self.scoreContent[i].maxScore)
				if (isNaN(score.score) || score.score < self.scoreContent[i].minScore || score.score > self.scoreContent[i].maxScore) {
					uni.showToast({
						title: '请检查评分项:' + score.scoreName + ',的分数是否正确',
						icon: 'none',
						duration: 2000
					});
					return;
				}
			}
			self.showUserVotedPopup = false;
		},
		async queryUserVoted() {
			uni.showLoading({
				title: '查询中',
				mask: true
			});
			const result = await self.$u.get(BASE_URL + "/vote/getUserVote", {itemId: self.itemId}, {'satoken': uni.getStorageSync('satoken')})
			uni.hideLoading();
			checkLogin(result, self.itemId);
			if (result.code === 200) {
				self.votesUser = result.data.votesUser;
				self.notVotesUser = result.data.notVotesUser;
				self.showPopup = true;
			} else {
				uni.showToast({
					title: result.msg ?? '查询失败',
					icon: 'none',
					duration: 2000
				});
			}
		},
		async checkVote() {
			const result = await self.$u.get(BASE_URL + "/vote/checkVote", {itemId: self.itemId}, {'satoken': uni.getStorageSync('satoken')})
			checkLogin(result, self.itemId);
			if (result.code === 200) {
				// 未投票
				self.isVote = false;
			} else {
				//已投票
				self.scoreMapList = result.data
				self.isVote = true;
			}
		},

		async changeSort(value) {
			self.isLoading = true;
			const result = await self.$u.get(BASE_URL + "/vote/list", {
				itemId: self.itemId,
				sort: self.sortChecked ? 'asc' : 'desc'
			}, {'satoken': uni.getStorageSync('satoken')})
			checkLogin(result, self.itemId);
			self.list = result.data.list;
			self.item = result.data.vote;
			self.isLoading = false;
		},
		startLoad() {
			timer = setInterval(async () => {
				if (self.isLoading) {
					return;
				}
				const result = await self.$u.get(BASE_URL + "/vote/list", {
					itemId: self.itemId,
					sort: self.sortChecked ? 'asc' : 'desc'
				}, {'satoken': uni.getStorageSync('satoken')})
				checkLogin(result, self.itemId);
				if (self.isLoading) {
					return;
				}
				self.list = result.data.list;
				self.item = result.data.vote;
			}, 2000)
		},
		async submitVote(sign) {
			const itemVoteSubs = getStore("itemVoteSubs");
			uni.showLoading({
				title: '投票中',
				mask: true
			});
			const itemVote = {
				itemId: self.itemId,
				sign: sign,
			}
			const result = await self.$u.post(BASE_URL + "/vote", JSON.stringify({itemVote, itemVoteSubs}),
				{'satoken': uni.getStorageSync('satoken'), "content-type": "application/json"})
			uni.hideLoading();
			// 检查是否登录
			checkLogin(result);
			if (result.code === 200) {
				uni.showToast({
					title: '投票成功',
					icon: 'none',
					duration: 2000
				});
				self.showUserVotedPopup = false;
				self.isVote = true;
			}
		},
		sureVote() {
			const itemVoteSubs = [];
			for (let i = 0; i < self.list.length; i++) {
				const vote = self.scoreMapList[self.list[i].id]
				if (!vote) {
					uni.showToast({
						title: `${self.list[i].name},还未评分`,
						icon: 'none',
						duration: 2000
					});
					return;
				}
				for (let j = 0; j < vote.length; j++) {
					const item = vote[j];
					if (!isNaN(item.score)) {
						item.score = parseFloat(item.score + '');
					}
					if (isNaN(item.score) || item.score < self.scoreContent[j].minScore || item.score > self.scoreContent[j].maxScore) {
						uni.showToast({
							title: `${self.list[i].name},评分项:${item.scoreName},分数不正确`,
							icon: 'none',
							duration: 2000
						});
						return;
					}
					itemVoteSubs.push(item);
				}
			}

			// // 获取,scoreMapList 中的所有value 然后遍历判断是否有空的
			// const values = Object.values(self.scoreMapList);
			//
			//
			// for (let i = 0; i < values.length; i++) {
			// 	const value = values[i];
			// 	for (let j = 0; j < value.length; j++) {
			// 		const item = value[j];
			// 		if (!isNaN(item.score)) {
			// 			item.score = parseFloat(item.score + '');
			// 		}
			// 		if (isNaN(item.score) || item.score < self.scoreContent[j].minScore || item.score > self.scoreContent[j].maxScore) {
			//
			//
			// 			uni.showToast({
			// 				title: '还有候选人分数未评完,请检查',
			// 				icon: 'none',
			// 				duration: 2000
			// 			});
			// 			return;
			// 		}
			// 		itemVoteSubs.push(item);
			// 	}
			// }

			// console.log(values.length, self.scoreContent.length)
			//暂存数据
			setStore("itemVoteSubs", itemVoteSubs)
			uni.navigateTo({
				url: '/pages/common/sign'
			});
		},
	}
	,
	onUnload() {
		if (timer) {
			clearInterval(timer);
		}
	}
	,
	async onLoad(query) {
		self = this;
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		self.itemId = query.itemId;
		const result = await self.$u.get(BASE_URL + "/vote/list", {itemId: self.itemId}, {'satoken': uni.getStorageSync('satoken')})
		checkLogin(result, self.itemId);
		uni.hideLoading();
		if (result.code === 200) {
			// 开启监听
			// todo 开发阶段关闭监听
			// setTimeout(() => {
			// 	self.startLoad();
			// }, 1000)
			self.list = result.data.list;
			self.item = result.data.vote;
			await self.checkVote();
		}
		//注册监听事件
		uni.$on('sign', (sign) => {
			//base64编码的图片
			if (!sign) {
				unis.showToast({
					title: '签名失败',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			self.submitVote(sign);
		})
	}
	,
	beforeDestroy() {
		if (timer) {
			clearInterval(timer);
		}
	}
	,
	computed: {
		totalValue() {
			return id => {
				return self.scoreMapList[id]?.reduce((total, item) => {
					return total + parseFloat(item.score);
				}, 0) ?? 0;
			}
		}
	},
	onShow() {

	}
}
</script>

<style>
.content {

}

.item {
	display: flex;
	align-items: center;
}

.item-right {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	margin-left: 10 rpx;
	font-size: 1.3rem;

}

</style>
